package io.gitee.welson.sensitive.strategy.impl;

import io.gitee.welson.sensitive.annotation.SensitiveStrategyComponent;
import io.gitee.welson.sensitive.strategy.SensitiveStrategy;
import io.gitee.welson.sensitive.util.SensitiveUtil;
import org.springframework.util.StringUtils;

/**
 * 地址脱敏策略
 * 规则：
 * 1. 保留省市区信息
 * 2. 对详细地址进行脱敏处理
 * 3. 支持通过参数指定保留的层级数（省市区街道等）
 * 用法示例：
 * @SensitiveField(
 *     strategy = AddressSensitiveStrategy.class,
 *     params = {"3"}  // 可选参数，保留的层级数，默认保留3级（省市区）
 * )
 *
 * @author welson
 */
@SensitiveStrategyComponent
public class AddressSensitiveStrategy implements SensitiveStrategy {

    /**
     * 默认保留3级（省市区）
     */
    private static final int DEFAULT_KEEP_LEVEL = 3;

    private static final String[] ADDRESS_SEPARATORS = {"省", "自治区", "市", "自治州", "区", "县", "旗", "镇", "街道"};

    @Override
    public String desensitize(String value, String... params) {
        if (!StringUtils.hasText(value)) {
            return value;
        }

        try {
            // 获取要保留的层级数
            int keepLevel = DEFAULT_KEEP_LEVEL;
            if (params != null && params.length > 0) {
                keepLevel = Integer.parseInt(params[0]);
            }

            // 分析地址结构
            AddressComponents components = parseAddress(value);
            
            // 如果解析失败，按照默认规则处理（保留30%内容）
            if (components == null) {
                int keepLength = Math.max(1, value.length() * 3 / 10);
                return SensitiveUtil.mask(value, keepLength, 0);
            }

            // 根据指定的层级数构建结果
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < keepLevel && i < components.levels.length; i++) {
                if (StringUtils.hasText(components.levels[i])) {
                    result.append(components.levels[i]);
                }
            }

            // 对剩余部分进行脱敏
            if (StringUtils.hasText(components.detail)) {
                result.append(SensitiveUtil.createMask(components.detail.length()));
            }

            return result.toString();
        } catch (Exception e) {
            // 如果处理过程出现异常，返回原值
            return value;
        }
    }

    private static class AddressComponents {
        String[] levels = new String[5]; // 存储省、市、区、街道等层级信息
        String detail; // 详细地址部分
    }

    private AddressComponents parseAddress(String address) {
        if (!StringUtils.hasText(address)) {
            return null;
        }

        AddressComponents components = new AddressComponents();
        String remaining = address;
        int levelIndex = 0;

        // 逐级解析地址
        for (String separator : ADDRESS_SEPARATORS) {
            int index = remaining.indexOf(separator);
            if (index >= 0) {
                // 找到分隔符，提取当前层级
                String level = remaining.substring(0, index + separator.length());
                components.levels[levelIndex++] = level;
                remaining = remaining.substring(index + separator.length()).trim();
            }
        }

        // 剩余部分作为详细地址
        if (StringUtils.hasText(remaining)) {
            components.detail = remaining;
        }

        return components;
    }
}